import {nextTick, onBeforeMount, reactive} from "vue";

export function createZdragXmlToolState() {
  let caozuoHeight = '100vh - 112px - 90px'

  let toolState = reactive({
    type: 'responsive',
    activeIndex:'2',
    defaultIndex: '2',
    showMenu: false,
    spans: [
      7,
      10,
      7,
    ],
    toolSpans: [
      9,
      6,
      9,
    ],
    maxCanvasHeight: `calc(${caozuoHeight})`,
    menuConHeight: `calc(${caozuoHeight})`,
    group: 'people__' + ZY.rid(6),
    toolbarHeight: '60px',
    panelHeaderHeight: '20px',
    scrollBarHeight: `calc(${caozuoHeight} - 21px)`,
    large: false
  })

  function adpatWindowSize() {
    let mql = window.matchMedia('(max-width:1200px)');
    let mql2 = window.matchMedia('(min-width:1599px)');
    // console.log('adpatWindowSize', mql.matches)
    if (mql.matches) {
      // toolState.viewMode = 'half-full'
      toolState.spans = [
        3, 10, 7
      ]
      // toolState.large = false
    } else {
      toolState.showMenu = false
      toolState.viewMode = 'default'
      toolState.spans = [
        7, 10, 7
      ]
      if (mql2.matches) {
        toolState.large = true
        toolState.spans = [
          5, 14, 5
        ]
      }
    }
  }

  // toolState.spans = [
  //   1, 16, 7
  // ]

  function isNeedToggleMenu() {
    if ( toolState.showMenu) {
      return false
    }
    return window.matchMedia('(max-width:1200px)')?.matches;
  }

  onBeforeMount(() => {
    adpatWindowSize()
  })

  let _resizeCurrentBuildInterval = null
  window.addEventListener('resize', function () {
    clearInterval(_resizeCurrentBuildInterval)
    // test3Tool()
    _resizeCurrentBuildInterval = setTimeout(function () {
      adpatWindowSize()
    }, 30)
  })

  function toggleShowMenu() {
    toolState.showMenu = !toolState.showMenu
    nextTick(() => {
      window.dispatchEvent(new CustomEvent('zdragxml__toogleMenu'))
    })
  }


  let last_known_scroll_position = 0;
  let ticking = false;

  function doSomething(scroll_pos) {
    // 根据滚动位置做的事
    // console.log(scroll_pos)
    nextTick(() => {
      window.dispatchEvent(new CustomEvent('zdragxml__toogleMenu'))
    })
  }

  window.addEventListener('scroll', function(e) {
    last_known_scroll_position = window.scrollX;

    if (!ticking) {
      window.requestAnimationFrame(function() {
        doSomething(last_known_scroll_position);
        ticking = false;
      });

      ticking = true;
    }
  });

  return {
    toggleShowMenu,
    isNeedToggleMenu,
    toolState
  }
}
